#!/bin/bash

INSTALL_BASE_DIR="$PWD/.."
INSTALL_DIR="$PWD"

echo "Installing FFMPEG ......"

# Install FFMPEG dependencies
echo "Installing dependencies ......"
apt-get update -qq --fix-missing && \
apt-get upgrade -y

apt-get -y install \
  pkg-config \
  build-essential \
  nasm \
  yasm \
  cmake \
  libtool \
  libc6 \
  libc6-dev \
  unzip \
  wget \
  libnuma1 \
  libnuma-dev \
  libx264-dev \
  git


# Download FFMPEG source
echo "Downloading FFMPEG source ......"

FFMPEG_VERSION="4.2.9"

mkdir -p "$INSTALL_BASE_DIR"/build

cd "$INSTALL_BASE_DIR"/build

echo "Installing ffnvcodec ......"

rm -rf nv-codec-headers

git clone https://git.videolan.org/git/ffmpeg/nv-codec-headers.git

cd "$INSTALL_BASE_DIR"/build/nv-codec-headers

git checkout origin/sdk/11.1

make install

cd "$INSTALL_BASE_DIR"/build

rm -rf ffmpeg
mkdir ffmpeg

#git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
wget -O ffmpeg-snapshot.tar.bz2 https://ffmpeg.org/releases/ffmpeg-"$FFMPEG_VERSION".tar.bz2

tar -xjvf ffmpeg-snapshot.tar.bz2 -C "$INSTALL_BASE_DIR"/build/ffmpeg --strip-components=1

cd "$INSTALL_BASE_DIR"/build/ffmpeg


# Install patch for FFMPEG which exposes timestamp in AVPacket
echo "Patching FFMPEG ......"
export FFMPEG_INSTALL_DIR="$INSTALL_BASE_DIR/build/ffmpeg"
export FFMPEG_PATCH_DIR="$INSTALL_DIR/ffmpeg_patch_4.2.9"

chmod +x "$FFMPEG_PATCH_DIR"/patch.sh
"$FFMPEG_PATCH_DIR"/patch.sh


# Compile FFMPEG
#echo "Configuring FFMPEG ......"
cd "$INSTALL_BASE_DIR"/build/ffmpeg 

# For RTX3060 with arch=compute_86
# For RTX4070 with arch=compute_89
./configure \
--enable-gpl \
--enable-nonfree \
--enable-cuda-nvcc \
--enable-libnpp \
--enable-libx264 \
--enable-nvenc \
--enable-nvdec \
--extra-cflags=-I/usr/local/cuda/include \
--extra-ldflags=-L/usr/local/cuda/lib64 \
--extra-libs="-lpthread -lm" \
--nvccflags="-gencode=arch=compute_86,code=compute_86" \
--disable-static \
--enable-shared

#Options for debug
#--enable-debug=3 \
#--disable-optimizations \
#--enable-shared \
#--disable-stripping

echo "Compiling FFMPEG ......"
make -j $(nproc) && \
make install && \
#hash -r
echo "Finished!!\n"
